<?php
//测试控制器类
class IndexController extends Controller{
    //动作方法
    public $dir;
    public function __init(){
    	define('__TEMPLATE__', __ROOT__.'/Template/jd');
    }
    public function index(){
    	$category = Data::channelLevel(M('category')->all());
    	// p($category);die;
		$this->assign('category',$category);
        //显示视图
        $this->display('Template/jd/index.html');
    }
    public function category(){
		$cid =Q('cid',0,'intval');
		$db = K('goodsData');
		if(!$s=Q("s")){
			$num = $db->getAttrNum();
			$sArg='';
			for($i=0;$i<$num;$i++){
				$sArg.='0-';
			}
			$sArg=trim($sArg,'-');
			
			$url = U('category',array('cid'=>$cid,'s'=>$sArg));
			go($url);
		}
		//读取 position
		$category= M('category')->all();
		$data = Data::parentChannel($category,$cid);
		$data = array_reverse($data);
		$this->assign('position',$data);
		// p($data);die;
		//读取该栏目商品
		$db = K('goodsData');
		$goods = $db->getAll();
		//获得商品的属性列表
		$attr =$db->getAttrList();
		$this->assign('attr',$attr);
		// p($attr);die;
		$this->assign('goods',$goods);
		$this->display('Template/jd/list.html');
	}
	public function goods(){
		$gid=Q('gid',0,'intval');
		//分配商品主表数据
		$goods  =M("goods")->find($gid);
		$this->assign('field',$goods);	
		//商品属性，用于选择指定款式的商品
		$gtid = M('category')->where("cid={$goods['cid']}")->getField('gtid');
		$attr = M('goods_attr')->where('gtid='.$gtid)->all();
		
		foreach($attr as $id=>$a){
			$sql="SELECT * FROM 
			jz_goods_attr_list as gal JOIN jz_goods_attr_value AS av
			ON gal.avid = av.avid
			WHERE gal.gid={$goods['gid']} AND av.attr_aid={$a['aid']}
			";
			$attr[$id]['_value']=M()->query($sql);
		}
		$this->assign('attr',$attr);
		// p($attr);die;
		$this->display('Template/jd/detail.html');
	}
	function getGoodsStock(){
		$sql ="";
		foreach($_GET['avid'] as $id=>$avid){
			$sql.="jz_stock_attr AS s{$id} JOIN ";
		}
		$sql =substr($sql,0,-5).'ON ';
		for($i=0;$i<count($_GET['avid']);$i++){
			$n=$i+1;
			if($n==count($_GET['avid']))break;
			$sql.="s{$i}.sid= s{$n}.sid";
		}
		$sql.=" JOIN jz_stock AS s ON s.sid=s{$id}.sid ";
		$sql.=' WHERE ';
		//设置条件 avid[]=4,7  根据AJAX来的属性值，确定一款商品
		foreach($_GET['avid'] as $id=>$avid){
			$sql.="s{$id}.avid={$avid} AND ";
		}
		$sql ="SELECT * FROM ".
		substr($sql,0,-4).' GROUP BY s.gid';
		$stock = M()->query($sql);
		if(empty($stock)){
			echo json_encode(array('status'=>'error'));
		}else{
			echo json_encode(array('status'=>'success','stock'=>$stock[0]));
		}
		exit;
	}
	public function tuichu(){
		unset($_SESSION['username']);
		go('index/index/index');
	}
}
